import { defineStore } from 'pinia'
import { VideoService } from '../../services/videoService'
import { TagService } from '../../services/tagService'
import { PAGES } from '../../constants'
import { handleError } from '../../utils/error'
import { normalizePath, addSafeFileProtocol } from '../../utils/file'

export const useVideoStore = defineStore('video', {
  state: () => ({
    currentVideo: null,
    currentTime: 0,
    tags: [],
    allTags: [],
    loading: false,
    isTagging: false,
    tagStartTime: null,
    currentPage: PAGES.SEARCH,
    searchState: {
      tags: [],
      currentInput: ''
    },
    recentTags: []
  }),
  
  actions: {
    async loadTags(videoPath) {
      this.loading = true
      try {
        const tags = await VideoService.getTags(videoPath)
        console.log('加载到标签数量:', tags.length)
        this.tags = tags
      } catch (error) {
        console.error('加载标签失败:', handleError(error))
      } finally {
        this.loading = false
      }
    },
    
    startTagging() {
      this.isTagging = true
      this.tagStartTime = this.currentTime
    },

    async endTagging({ description, color }) {
      if (!this.isTagging || this.tagStartTime === null) return
      
      try {
        const normalizedPath = normalizePath(this.currentVideo.originalPath)
        const video = await VideoService.createOrUpdateVideo(normalizedPath, this.currentVideo.name)
        
        await TagService.createTag(video.id, {
          description,
          color,
          startTime: this.tagStartTime,
          endTime: this.currentTime
        })
        
        this.addRecentTag({ description, color })
        
        // 重新加载标签
        await this.loadTags(normalizedPath)
      } catch (error) {
        console.error('添加标签失败:', handleError(error))
      } finally {
        this.isTagging = false
        this.tagStartTime = null
      }
    },

    addRecentTag({ description, color }) {
      this.recentTags = this.recentTags.filter(tag => tag.description !== description)
      
      this.recentTags.unshift({ description, color })
      
      this.recentTags = this.recentTags.slice(0, 5)
    },

    cancelTagging() {
      this.isTagging = false
      this.tagStartTime = null
    },

    async deleteTag(tagId) {
      try {
        await TagService.deleteTag(tagId)
        await this.loadTags(normalizePath(this.currentVideo.originalPath))
      } catch (error) {
        console.error('删除标签失败:', handleError(error))
      }
    },

    async updateTag(tagId, { description, color }) {
      try {
        await TagService.updateTag(tagId, { description, color })
        this.addRecentTag({ description, color })
        await this.loadTags(normalizePath(this.currentVideo.originalPath))
      } catch (error) {
        console.error('更新标签失败:', handleError(error))
      }
    },

    async searchTags(query) {
      try {
        this.allTags = await VideoService.searchTags(query)
      } catch (error) {
        console.error('搜索标签失败:', handleError(error))
        this.allTags = []
      }
    },

    setCurrentPage(page) {
      this.currentPage = page
      if (page === PAGES.SEARCH) {
        this.cancelTagging()
        this.currentVideo = null
        this.tags = []
        if (this.searchState.tags.length > 0) {
          this.searchTags(this.searchState.tags.join(' '))
        }
      }
    },

    saveSearchState(tags, currentInput) {
      this.searchState = {
        tags,
        currentInput
      }
    },

    async updateVideoInfo(videoPath) {
      try {
        await VideoService.createOrUpdateVideo(
          normalizePath(videoPath),
          this.currentVideo.name
        )
      } catch (error) {
        console.error('更新视频信息失败:', handleError(error))
      }
    }
  }
}) 